<?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Requests;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Controllers\Controller;
use App\Libraries\ValidateCode;
use Hash;
use DB;
class RegisterController extends Controller
{
	//注册
    public function register()
    {
    	// return 111;
    	return view('home/register/register');
    }

    public function doRegister(Request $request)
    {
         $data = $request -> except('_token','code');
        // dd($data); 
       
        $this->validate($request, [
            //验证规则，required(不为空)
             'name' => 'required|min:2|max:10',
            'password' => 'required|min:4|max:8',
            'repassword' => 'required|same:password',
            'phone' => 'required|numeric',
            'code' => 'required',
        ],[
             // //错误提醒
             'name.required' => '会员名称不能为空',
             'name.min' => '会员名称在0~10位',
             'name.max' => '会员名称在0~10位',
             'password.required' => '密码不能为空',
             'password.min' => '密码4~8位',
             'password.max' => '密码4~8位',
             'repassword.required' => '确认密码不能为空',
             'repassword.same' => '确认密码与密码不一致',
             'phone.required' => '手机号码不能为空', 
             'phone.numeric' => '手机号格式不正确或少于11位',
             'code.required' => '验证码不能为空',             
        ]);       
        $name = DB::table('member') -> lists('name');
         $request -> flash(); 
        if(in_array($data['name'],$name))
        {
            return back() -> with(['error' => '该账号已注册，请重新输入']);
        }

         // 检测验证码
        $code = $request -> input('code');
        // dd(session('code'));
        $request -> flash();      
        if($code != session('code'))
        {
            return back() -> with(['error' => '验证码错误']);
        }

        // 删除repassword
        unset($data['repassword']);
        //密码加密;
        $data['password'] = Hash::make($data['password']);

        //处理登录状态,1离线2在线
        $data['logged'] = 2;

        //处理禁用状态,1可用2禁用
        $data['disabled'] = 1;

        //处理会员昵称
        $data['nickname'] = $data['name'];

        //处理会员注册时间
        $data['rtime'] = time();

        // 执行添加
        $res = DB::table('member') -> insert($data);
        // dd($res);
        //判断;       
        if($res)
        {
            return redirect('admin/index') -> with(['success' => '添加成功']);
        }else
        {
            return back() -> with(['error' => '注册失败']);
        }    
    }


    //生成验证码
    public function createCode($id)
    {   
        $vc=new ValidateCode();
        $vc->doimg();
        session(['code' => $vc->getCode()]);
        
    }
}
